<?php

class Edit extends TPage
{
	private $user_manager;
	private $user;
	
	public function onLoad($param)
	{
		parent::onLoad($param);
		
		//if($this->User->getIsGuest())
		//	$this->Response->redirect($this->Service->constructUrl('AccessDenied'));
	
		$this->user_manager = $this->Application->Modules['users'];
		$id = $this->Application->Request['id'];
		if(!$id)
			$id = $this->User->getName();
			
		if($id != $this->User->getName() && !$this->User->getIsAdmin())
			;//$this->Response->redirect($this->Service->constructUrl('AccessDenied'));
		
		$this->user = $this->user_manager->getUserById($id);
		if($this->user instanceof UserRecord)
		{
			if(!$this->Page->getIsPostback())
			{
				$this->readDataFromUser();
			}
		}
		else
			;//$this->Response->redirect($this->Service->constructUrl('AccessDenied'));
	}
	
	public function readDataFromUser()
	{
		$this->login->Text = $this->user->getLogin();
		$this->email->Text = $this->user->getEmail();
		$this->first_name->Text = $this->user->getFirstName();
		$this->last_name->Text = $this->user->getLastName();
	}
	
	public function savePersonalDataButtonClicked($sender, $params)
	{
		$this->personal_data_info->Text = '';
		if($this->IsValid == false)
			return;
		if($this->user instanceof UserRecord)
		{
			$this->user->setEmail($this->email->Text);
			$this->user->setFirstName(String::format($this->first_name->Text));
			$this->user->setLastName(String::format($this->last_name->Text));
			
			if($this->user_manager->updateUserByUserRecord($this->user))
				$this->personal_data_info->Text = '<p>'.Prado::localize('Changes saved').'</p>';
			else
				$this->personal_data_info->Text = '<p>'.Prado::localize('Changes not saved').'</p>';
		}
	}
	
	public function savePasswordButtonClicked($sender, $params)
	{
		$this->personal_data_info->Text = '';
		if($this->IsValid == false)
			return;
		if($this->user instanceof UserRecord)
		{
			$this->user->setPassword($this->new_password->Text);
			
			if($this->user_manager->updateUserByUserRecord($this->user))
				$this->password_data_info->Text = '<p>'.Prado::localize('Changes saved').'</p>';
			else
				$this->password_data_info->Text = '<p>'.Prado::localize('Changes not saved').'</p>';
		}
	}
	
	public function validatePassword($sender,$param)
	{
		if($this->user instanceof UserRecord && $this->old_password->Text == $this->user->getPassword())
			$param->IsValid = true;
		else
			$param->IsValid = false;
	}
}

?>